# @Create  : 2021/12/29 11:07
# @Author  : Palm
# @Remark  : 统计报表DB层
import time
import logging
from datetime import datetime
from itertools import zip_longest
from mxsoftpy import DB
from mxsoftpy.exception import DataError
from index import _ as zh_error


class ReportFormDB(DB):
    def __init__(self):
        super().__init__()
        self.open_param = {'file': 'Co_1', 'main_key': 'RP_RaelTime'}
        self.conn = self.tree.open(**self.open_param)

    def create(self, **params):
        report_code = self.tree.open(**self.open_param).insert_key_items(params)
        logging.info('新增了一个实时报告：%s' % report_code)
        logging.debug('新增的计划详情：%s' % str(params))
        return report_code

    def select(self, **params):
        res, key_list = self.tree.open(**self.open_param).filter(**params)
        if res != 0:
            res = self.tree.open(**self.open_param).sub_items(key_list)
            return res
        else:
            return []

    def delete(self, code_list):
        self.tree.begin()
        # noinspection PyBroadException
        try:
            self.tree.open(**self.open_param).delete(code_list)
            self.tree.commit()
            if isinstance(code_list, list):
                del_count = len(code_list)
            else:
                del_count = 1
        except:
            self.tree.rollback()
            del_count = 0
        return del_count

    def retrieve(self, code):
        open_param = self.open_param
        open_param['sub_key'] = code
        conn = self.tree.open(**open_param)
        res = conn.items()
        return res

    def update(self, **params):
        open_param = self.open_param
        open_param['sub_key'] = params.pop('code')
        conn = self.tree.open(**open_param)
        report = conn.insert_items(params)
        return report

    def items(self, code, item_list):
        open_param = self.open_param
        open_param['sub_key'] = code
        conn = self.tree.open(**open_param)
        return conn.items(item_list)

    def filter_ccubase(self, filter_dict):
        conn = self.tree.open('IRM_Device', file='Co_1')
        res = conn.filter(**filter_dict)
        return res

    def get_last_report(self, table_path):
        conn = self.table.open(file="MXSE", table=table_path)
        res = conn.record_by_time(days=10, count=1)
        return res

    def get_ccubase_item(self, device_id, item):
        open_param = {'file': 'Co_1', 'main_key': 'IRM_Device', 'sub_key': device_id}
        conn = self.tree.open(**open_param)
        mxlabel = conn.items([item])
        return mxlabel

    def get_base_items(self, main_key, sub_key, prop_list):
        open_param = {'file': 'base', 'main_key': main_key, 'sub_key': sub_key}
        conn = self.tree.open(**open_param)
        res = conn.items(prop_list)
        return res
